let api = require('../../../api/index');
let util = require('../../../utils/util');

Page({
    data: {
        image: '',
        tabIndex: 0, // 点击的tab
        tit_list: [{
                time: '24:00',
                text: '即将开始',
                timeSearch: {},
                is_qg: false
            },
            {
                time: '06:00',
                text: '抢购中',
                timeSearch: {},
                is_qg: true
            },
            {
                time: '18:00',
                text: '即将开始',
                timeSearch: {},
                is_qg: false
            },
            {
                time: '21:00',
                text: '即将开始',
                timeSearch: {},
                is_qg: false
            }
        ],
        active: 0, // [当前活动]key
        countDownArrray: ['00', '00', '00'], // [当前活动]倒计时
        countDownTimer: null, // [当前活动]倒计时timer
        list: [], // 表单列表
        form: {
            page: 1,
            pagesize: 10,
        },
        pageStatus: 1, // 1下拉加载更多..  5加载中... 10没有更多了... 99暂无数据
        timer: null // 商品检索倒计时
    },
    onLoad: function (options) {

    },
    onShow: function () {
        this.reload()
    },
    onReady: function () {

    },
    onHide: function () {
        this.setTimeoutStop()
        this.countDownTimerStop()
    },
    onUnload: function () {
        this.setTimeoutStop()
        this.countDownTimerStop()
    },
    onPullDownRefresh: function () {
        console.log('打印日志，要不然会出现一个版本bug')

        wx.startPullDownRefresh()

        setTimeout(() => {
            this.getList('reset')

            // 停止下拉刷新
            wx.stopPullDownRefresh()
        }, 50)

        return true
    },
    onReachBottom: function () {
        this.getList()
    },
    // onShareAppMessage: function () {

    // },
    reload() {
        console.log('初次加载')
        this.tabTimeChange(true)
        this.getList('reset')
        this.getImage()
    },
    getImage(){
        let that = this
        api.doctor.getActivityImage().then(res => {
            console.log(res)
            res.data.ResData.map( e => {
                console.log(e)
                if(e.type == 4){
                    that.setData({
                        image: e.image
                    })
                }
            })
        })
    },
    getList(type) {
        if (type === 'reset') {
            this.setTimeoutStop();

            this.setData({
                ['form.page']: 1,
                // list: [],
                pageStatus: 1
            })
        }


        if (this.data.pageStatus !== 1) {
            return false
        } else {
            this.setData({
                pageStatus: 5
            })
        }

        api.goods.getGoodsSkill({
            page: this.data.form.page,
            pagesize: this.data.form.pagesize,
            ...this.data.tit_list[this.data.active].timeSearch
        }).then(res => {
            let list = res.data.ResData.Items
            let pageSize = res.data.ResData.ItemsPerPage
            let pageStatus;


            list.map((item, index) => {
                let timeText = item.StartTime.substring(11, 16);
                let titleText = item.Title.substring(0, 4);

                item.timeText = timeText
                item.titleText = titleText
            })

            if (this.data.list.pageNum > 1) {
                list = this.data.list.concat(list);
            }

            if (list.length < pageSize) {
                if (list.length <= 0) {
                    pageStatus = 99
                } else {
                    pageStatus = 10
                }
            } else {
                pageStatus = 1
            }

            this.setData({
                list: list,
                pageStatus: pageStatus,
                ['form.page']: this.data.form.page++,
            }, function () {
                if (type === 'reset') {
                    this.setTimeoutOpen()
                }
            })
        })
    },
    // 定时任务检索
    setTimeoutOpen() {
        this.setTimeoutStop()

        this.listStartChange()

        this.data.timer = setInterval(() => {
            // console.log('商品定时任务')
            this.listStartChange()
        }, 1000)
    },
    setTimeoutStop() {
        if (this.data.timer) {
            clearInterval(this.data.timer)
            this.data.timer = null
        }
    },
    /**
     * 列表数据发生变化
     */
    listStartChange() {
        let time = parseInt(new Date().getTime() / 1000)

        let list = this.data.list.map((item, index) => {
            // console.log(item)
            let startTime = util.dateToTime(item.StartTime)
            let endTTime = util.dateToTime(item.EndTime)

            if (startTime <= time && time <= endTTime) {
                item.isBuy = true
            } else {
                if (time >= endTTime) {
                    item.buttenText = '已结束'
                } else if (time <= startTime) {
                    item.buttenText = '待开场'
                }

                item.isBuy = false
            }


            this.setData({
                ['list[' + index + ']']: item
            })

            return item
        })


        this.setData({
            list
        })
        // console.log(this.data.list,"listlllll");
    },
    // 栏目时间变化
    tabTimeChange(isChangeTab = false) {
        let date = new Date();
        const year = date.getFullYear()
        const month = date.getMonth() + 1
        const day = date.getDate()


        let tit_list = this.data.tit_list;
        tit_list[0].timeSearch = {
            'start_time': `${year}-${month}-${day} 00:00:00`,
            'end_time': `${year}-${month}-${day} 05:59:59`,
        }
        tit_list[1].timeSearch = {
            'start_time': `${year}-${month}-${day} 06:00:00`,
            'end_time': `${year}-${month}-${day} 17:59:59`,
        }
        tit_list[2].timeSearch = {
            'start_time': `${year}-${month}-${day} 18:00:00`,
            'end_time': `${year}-${month}-${day} 20:59:59`,
        }
        tit_list[3].timeSearch = {
            'start_time': `${year}-${month}-${day} 21:00:00`,
            'end_time': `${year}-${month}-${day} 23:59:59`,
        }

        let currentTime = new Date().getTime() / 1000;
        let time0 = parseInt(new Date(`${year}/${month}/${day} 00:00:00`).getTime() / 1000)
        let time1 = parseInt(new Date(`${year}/${month}/${day} 06:00:00`).getTime() / 1000)
        let time2 = parseInt(new Date(`${year}/${month}/${day} 18:00:00`).getTime() / 1000)
        let time3 = parseInt(new Date(`${year}/${month}/${day} 21:00:00`).getTime() / 1000)
        let time4 = parseInt(new Date(`${year}/${month}/${day} 23:59:59`).getTime() / 1000)

        let active = 0
        if (time0 <= currentTime && currentTime < time1) {
            active = 0
        } else if (time1 <= currentTime && currentTime < time2) {
            active = 1
        } else if (time2 <= currentTime && currentTime < time3) {
            active = 2
        } else if (time3 <= currentTime && currentTime < time4) {
            active = 3
        }

        tit_list = tit_list.map((item, index) => {
            let activeText;

            if (active == index) {
                activeText = '抢购中'
            } else if (active > index) {
                activeText = '已结束'
            } else if (active < index) {
                activeText = '即将开始'
            }

            item.text = activeText

            return item
        })


        this.setData({
            active,
            tit_list
        })

        if (isChangeTab) {
            this.setData({
                tabIndex: active
            })
        }

        this.countDownTimerOpen()
    },
    countDownTimerOpen() {
        this.countDownTimerStop()

        this.countDownTimerContent()

        this.data.countDownTimer = setInterval(() => {
            // console.log('倒计时定时任务')
            this.countDownTimerContent()
        }, 1000)
    },
    countDownTimerStop() {
        if (this.data.countDownTimer) {
            clearInterval(this.data.countDownTimer)
            this.data.countDownTimer = null
        }
    },
    countDownTimerContent() {
        let timeArray = this.data.tit_list[this.data.active].timeSearch
        let endTime = util.dateToTime(timeArray.end_time)
        let countDownNumber = endTime - parseInt(new Date().getTime() / 1000)
        // console.log('倒计时', countDownNumber)
        if (countDownNumber <= 0) {
            this.active++


            if (this.active >= 4) {
                // 更新到下一天,重新计时
                this.active = 0
                this.tabTimeChange()
            } else {
                // 未跨天
                this.setData({
                    active: this.active,
                    tabIndex: this.active
                })

                this.countDownTimerContent()
            }
        } else {
            let countDownArrray = util.numberToCountDown(countDownNumber)
            this.setData({
                countDownArrray: countDownArrray
            })
        }

    },
    active_fn(el) {
        let index = el.currentTarget.dataset.index
        this.setData({
            tabIndex: index
        })

        this.getList('reset')
    },
    toPagesDetails(e) {
        console.log(e)
        let info = e.currentTarget.dataset.item;
        console.log(info)
        if (info.isBuy) {
            wx.navigateTo({
                url: `/pages/product/detail/detail?source=miaosha&id=${info.Id}&goodsId=${info.GoodsId}`,
            })
        }
    }
})